package com.zlcx.tz.live.service.impl;

import com.zlcx.tz.live.constant.RedisKeyConst;
import com.zlcx.tz.live.constant.UseState;
import com.zlcx.tz.live.domain.LiveAgoraAcount;
import com.zlcx.tz.live.exception.BusinessException;
import com.zlcx.tz.live.repository.LiveAgoraAcountRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author zl
 * @version 1.0
 * @date Created in 2019/5/22 09:09
 * @copyright: Copyright (c) founders
 */
@Slf4j
@Service
public class LiveAgoraAcountService {

    @Autowired
    private LiveAgoraAcountRepository liveAgoraAcountRepository;

    @Autowired
    RedisTemplate redisTemplate;


    public LiveAgoraAcount getCurrentUseAcountCache(){
        LiveAgoraAcount liveAgoraAcount = null;
        String currentPublishingRecordKey = RedisKeyConst.getCurrentAgoraAcountKey();
        try {
            liveAgoraAcount = (LiveAgoraAcount) redisTemplate.opsForValue().get(currentPublishingRecordKey);
            if(liveAgoraAcount!=null){
                return liveAgoraAcount;
            }
        }catch (Exception e){
            log.error("redis get {} error,e={}",currentPublishingRecordKey,e);
        }

        liveAgoraAcount = getCurrentUseAcount();

        if(liveAgoraAcount!=null){
            try {
                redisTemplate.opsForValue().set(currentPublishingRecordKey,liveAgoraAcount,1, TimeUnit.DAYS);
            }catch (Exception e){
                log.error("redis set {} error,e={}",currentPublishingRecordKey,e);
            }
        }

        return liveAgoraAcount;

    }

    private LiveAgoraAcount getCurrentUseAcount(){
        LiveAgoraAcount liveAgoraAcount = liveAgoraAcountRepository.findFirstByUseState(UseState.active.getCode());
        return liveAgoraAcount;

    }

    public void activeAppid(String appId){

        LiveAgoraAcount liveAgoraAcount = liveAgoraAcountRepository.findFirstByAppId(appId);
        if(liveAgoraAcount==null){
            throw new BusinessException("appID不存在");
        }

        Date now = new Date();
        liveAgoraAcount.setUseState(UseState.active.getCode());
        liveAgoraAcount.setUpdateTime(now);
        liveAgoraAcountRepository.save(liveAgoraAcount);
        liveAgoraAcountRepository.abandonActiveAcount(appId,now);

        redisTemplate.delete(RedisKeyConst.getCurrentAgoraAcountKey());

    }












}
